const app = getApp()
Page({
  data: {
    messageList: [],
    unreadCount: 0,
    showDetailModal: false,
    currentMessage: null,
	pageSize:10,
	currentPage:1,
    isLoading: false,      // 是否正在加载
    hasMore: true,         // 是否有更多数据
	unreadCount:0,
  },

  onLoad: function() {
    this.loadMessageList();
  },

  // 加载消息列表
  loadMessageList: function() {
	  var that = this
	  
	  const { currentPage, pageSize } = this.data;
	  app.util.request({
	  	url: 'message/getlist',
	  	data: {
	  		page_no:that.data.currentPage,
			page_size:that.data.pageSize
	  	},
	  	success(res) {
			console.log('data:',data)
	  		const start = (currentPage - 1) * pageSize;
			const end = start + pageSize;
			var data = res.data.data;
			var list = data.list || []
			that.setData({
			  messageList: [...that.data.messageList,...list],
			  currentPage: currentPage + 1,
			  hasMore: end < data.total,
			  isLoading: false,
			  unreadCount:data.unreadCount
			});
	  	}
	  })
  },
// 下拉加载更多
  onReachBottom: function() {
    if (!this.data.isLoading && this.data.hasMore) {
      this.loadMessageList();
    }
  },
  // 显示消息详情
  showMessageDetail: function(e) {
    const message = e.currentTarget.dataset.item;
    
    // 标记为已读
    if (!message.isRead) {
      this.markAsRead(message.rec_id);
    }

    this.setData({
      currentMessage: message,
      showDetailModal: true
    });
  },

  // 标记单条消息为已读
  markAsRead: function(messageId) {
    var that = this
      app.util.request({
    	url: 'message/setMessageForRead',
    	data: {
    		rec_id:messageId
    	},
    	success(res) {
    		that.setData({
    		  currentPage: 1,
			  messageList:[]
    		});
    		wx.showToast({
    		  title: '全部标记为已读',
    		  icon: 'success'
    		});
    		that.loadMessageList()
    	}
      })
  },

  // 全部标记为已读
  markAllAsRead: function() {
    if (this.data.unreadCount === 0) return;

    var that = this
	  app.util.request({
		url: 'message/setMessageForRead',
		data: {
			
		},
		success(res) {
			
			that.setData({
			  currentPage: 1,
			  messageList:[]
			});
			wx.showToast({
			  title: '全部标记为已读',
			  icon: 'success'
			});
			that.loadMessageList()
		}
	  })

    
  },

  // 关闭弹窗
  closeModal: function() {
    this.setData({
      showDetailModal: false,
      currentMessage: null
    });
  }
});